package com.itheima.service;

import com.itheima.exception.BusinessException;
import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.UserInfoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    //更新用户头像
    public void updateHead(MultipartFile headPhoto, Long id) {
        //将图片上传到aliyunoss
        String imageUrl = null;
        try {
            imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        //调用百度云判断是否包含人脸
        boolean detect = aipFaceTemplate.detect(imageUrl);
        //如果不包含人脸，抛出异常
        if(!detect){
            throw new BusinessException(ErrorResult.faceError());
        }else {
            //包含人脸，调用API更新
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo.setAvatar(imageUrl);
            userInfoApi.update(userInfo);
        }
    }

    //根据id查询用户信息
    public UserInfoVo findById(Long userID) {
        UserInfo userInfo = userInfoApi.findById(userID);

        UserInfoVo userInfoVo = new UserInfoVo();

        BeanUtils.copyProperties(userInfo,userInfoVo);//copy同名同类型的属性

        if(userInfo.getAge() != null){
            userInfoVo.setAge(userInfo.getAge().toString());
        }

        return userInfoVo;
    }

    //更新用户资料
    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }
}
